﻿namespace YunQue.Core.WebExtension.Extensions
{
    public static class WebAppExtension
    {
        /// <summary>
        /// 自定义的中间件配置
        /// </summary>
        /// <param name="app"></param>
        public static void UseWebAppCustomConfig(this WebApplication app)
        {
            // 全局异常处理
            app.UseExceptionHandler((errorApp) =>
            {
                errorApp.Run(async context =>
                {
                    var logHelper = context.RequestServices.GetRequiredService<LogHelper>();
                    var exception = context.Features.Get<IExceptionHandlerFeature>();
                    int statusCode = exception.Error switch
                    {
                        ArgumentNullException => 400, // 参数为空异常
                        UnauthorizedAccessException => 401, // 未授权异常
                        KeyNotFoundException => 404, // 找不到资源异常
                        _ => 500 // 默认服务器错误
                    };
                    context.Response.StatusCode = 200;
                    context.Response.ContentType = "application/json";
                    // 构造统一的返回格式
                    var apiResponse = new ApiResultModel<object>
                    {
                        Code = statusCode,// 异常状态码
                        Message = exception.Error.Message,
                        Data = null
                    };
                    await context.Response.WriteAsJsonAsync(apiResponse);
                });
            });
            // 用户上下文中间件
            app.UseMiddleware<UserContextMiddleware>();
            // 登录权限控制
            app.UseMiddleware<LoginPermissionMiddleware>();
            //租户级别的权限控制
            app.UseMiddleware<APIPermissionMiddleware>();
        }
    }
}
